<?php

namespace App\Console\Commands;

use App\Http\Controllers\Open\XgController;
use App\Jobs\SpiderJob;
use App\Models\Administrator;
use App\Models\Content;
use App\Models\Role;
use App\Services\Spider\BaiduDrive;
use App\Services\Spider\WuzhuisoDrive;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Queue\Queue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class XgSpiderComm extends Command
{
    protected $signature = 'xg:spider-keyword-comm';

    protected $description = '批量采集baidu关键词保存JOB数据库内';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
//        self::BatchSpider();
//        echo '\r\n\r\n执行完成!!!\r\n\r\n';
//        return

        $keylists = DB::table('wiki_searchkeyword')->where(['status'=>0])->limit(50)->select()->get()->toArray();
        //`status` 0表示有效，-1表示删除，1表示已经用过',

        foreach ($keylists as $k=>$keywordInfo) {
            $time = date("H:i:s");
            $keywordInfo->site_id = 2;
            echo "\r\n  No: " .($k-0+1)."; time:{$time} ; site_id : {$keywordInfo->site_id}; searchkeyword : {$keywordInfo->searchkeyword} >>>> ";
            self::createSchema($keywordInfo->site_id);
            $job = new SpiderJob($keywordInfo);
            dispatch($job);
        }

    }

    public static function BatchSpider() {

        $keylists = DB::table('wiki_searchkeyword')->where(['status'=>0])->limit(20)->select()->get()->toArray();
        //`status` 0表示有效，-1表示删除，1表示已经用过',

        foreach ($keylists as $k=>$keywordInfo) {
            $time = date("H:i:s");
            echo "\r\n  No: " .($k-0+1)."; time:{$time} ; site_id : {$keywordInfo->site_id}; searchkeyword : {$keywordInfo->searchkeyword} >>>> ";

            self::createSchema($keywordInfo->site_id);
//            $wuzhuisoDrive = new WuzhuisoDrive();
//            $wuzhuisoDrive->claws($keywordInfo->searchkeyword);  //异步开始

            $drive = new BaiduDrive();
            $drive->claws($keywordInfo->searchkeyword);
        }

    }


    private static function createSchema($site_id) {
        $site_id = 2;  //2表示ggiooo.com的chatGPT内容
        $tabname = 'wiki_spider_'.$site_id;
        if (!Schema::hasTable($tabname)) {
            // 如果表不存在,则创建表
            Schema::create($tabname, function (Blueprint $table) {
                $table->bigIncrements('id'); // 使用 bigIncrements 方法设置 id 为自增主键
                $table->integer('site_id')->default(0)->required();
                $table->integer('keyword_id')->default(0)->required()->unique();
                $table->text('title')->required();
                $table->integer('is_delete')->default(0);
                $table->timestamps(); // 添加时间戳
            });
        }
        $tabname = 'wiki_spider_data_'.$site_id;
        if (!Schema::hasTable($tabname)) {
            // 如果表不存在,则创建表
            Schema::create($tabname, function (Blueprint $table) {
                $table->bigIncrements('id'); // 使用 bigIncrements 方法设置 id 为自增主键
                $table->integer('spider_id')->default(0)->required();
                $table->text('content')->required();
                $table->integer('pn')->default(0)->required();
                $table->timestamps(); // 添加时间戳
            });
        }

    }

    //异步回调
    public static function CallSpiderResult($news,$keyword,$pn) {
        $articles = [];
        foreach($news as $k2=>$v2) {
            if ($v2['title'] && $v2['short_article']) {
                $articles[] = "<h3>".$v2['title']."</h3>";
                $articles[] =  "<p>".$v2['short_article']."</p>";
            }
        }

        if (count($articles)==0) {
            return false;
        }

        $keywordInfo = DB::table('wiki_searchkeyword')->where(['searchkeyword'=>$keyword])->first();

        DB::table('wiki_searchkeyword')->where(['id'=>$keywordInfo->id])->update(['status'=>1,'created_time'=>date("Y-m-d H:i:s")]);

        $siteInfo =  DB::table('wiki_spider_'.$keywordInfo->site_id)->where("keyword_id",$keywordInfo->id)->first();
        echo "; keyword_id={$keywordInfo->id} ;";
        if ($siteInfo) {
            $newId = $siteInfo->id;
        } else {
            $newId = DB::table('wiki_spider_'.$keywordInfo->site_id)->insertGetId([
                'site_id' => $keywordInfo->site_id,
                'keyword_id' => $keywordInfo->id,
                'title' => $news[0]['title'],
                'created_at' => date("Y-m-d H:i:s"),
                'updated_at' => date("Y-m-d H:i:s")
            ]);
//            echo PHP_EOL.'  记录新增成功!!!'.date("Y-m-d H:i:s");
        }

        $articles2 = htmlspecialchars(implode("", $articles), ENT_QUOTES, 'UTF-8');
        DB::table('wiki_spider_data_'.$keywordInfo->site_id)->insert([
            'spider_id' =>$newId,
            'content' => $articles2,
            'pn'=>$pn,
            'created_at' => date("Y-m-d H:i:s"),
            'updated_at' => date("Y-m-d H:i:s"),
        ]);
        echo PHP_EOL.'  明细内容--新增成功!!!'.date("Y-m-d H:i:s");
    }


}
